package cn.iocoder.yudao.module.system.api.sms;
import cn.iocoder.yudao.framework.common.core.KeyValue;
import com.google.common.collect.Lists;

import cn.iocoder.yudao.module.system.api.sms.dto.send.SmsSendSingleToUserReqDTO;
import cn.iocoder.yudao.module.system.mq.message.sms.SmsSendMessage;
import cn.iocoder.yudao.module.system.service.sms.SmsSendService;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.system.enums.ErrorCodeConstants.SMS_SEND_MOBILE_TEMPLATE_PARAM_MISS;

/**
 * 短信发送 API 接口
 *
 * @author 芋道源码
 */
@Service
@Validated
public class SmsSendApiImpl implements SmsSendApi {

    @Resource
    private SmsSendService smsSendService;

    @Override
    public Long sendSingleSmsToAdmin(SmsSendSingleToUserReqDTO reqDTO) {
        return smsSendService.sendSingleSmsToAdmin(reqDTO.getMobile(), reqDTO.getUserId(),
                reqDTO.getTemplateCode(), reqDTO.getTemplateParams());
    }

    @Override
    public Long sendSingleSmsToMember(SmsSendSingleToUserReqDTO reqDTO) {
        return smsSendService.sendSingleSmsToMember(reqDTO.getMobile(), reqDTO.getUserId(),
                reqDTO.getTemplateCode(), reqDTO.getTemplateParams());
    }


    @Override
    public void sendSingleSmsDirectToMobile(SmsSendSingleToUserReqDTO reqDTO) {
        List<KeyValue<String, Object>> templateParamsList = Lists.newArrayList();
        Map<String, Object> templateParams = reqDTO.getTemplateParams();
        //HashMap 转化为 KeyValue<String, Object>
        templateParams.forEach((k, v) -> templateParamsList.add(new KeyValue<>(k, v)));
        SmsSendMessage message = new SmsSendMessage();
        message.setMobile(reqDTO.getMobile());
        message.setChannelId(reqDTO.getChannelId());
        message.setApiTemplateId(reqDTO.getTemplateCode());
        message.setTemplateParams(templateParamsList);
        smsSendService.doSendSms(message);
    }

}
